package com.digital.welcome.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.digital.welcome.entity.College;
import com.digital.welcome.entity.UserCollege;
import com.digital.welcome.mapper.CollegeMapper;
import com.digital.welcome.mapper.UserCollegeMapper;
import com.digital.welcome.response.Result;
import com.digital.welcome.service.CollegeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class CollegeServiceImpl extends ServiceImpl<CollegeMapper, College> implements CollegeService {
    @Autowired
    private CollegeMapper collegeMapper;
    @Autowired
    private UserCollegeMapper userCollegeMapper;
    @Override
    public String getCollegeList()
    {
        List<College> collegeList = null;
        collegeList = collegeMapper.selectList(null);// 查询所有数据表数据并遍历输出,不填写就是无任何条件
        return JSON.toJSONString(new Result<>().setCode(1).setMessage("查询成功").setData(collegeList));
    }

    @Override
    public String insertCollege(String college) {
        QueryWrapper<College> wrapper=new QueryWrapper<>();
        wrapper.eq("college",college);
        if(collegeMapper.selectCount(wrapper)>0){
            return JSON.toJSONString(new Result<>().setCode(400).setMessage("已存在该学院"));
        }
        try{
           QueryWrapper<College> map= new QueryWrapper<>();
           Integer integer = collegeMapper.selectCount(map)+1;
           collegeMapper.insertCollege(college,integer);
           return JSON.toJSONString(new Result<>().setCode(200).setMessage("新增成功"));
       }
       catch (Exception e){
           return JSON.toJSONString(new Result<>().setCode(400).setMessage("新增失败"));
       }
    }

    @Override
    public String deleteCollege(String college) {
        QueryWrapper<UserCollege> queryWrapper=new QueryWrapper<>();
        College collegeObject = collegeMapper.selectByName(college);
        queryWrapper.eq("college_id", collegeObject.getCollegeId());
        Integer count= userCollegeMapper.selectCount(queryWrapper);
        if(count>0){
            return JSON.toJSONString(new Result<>().setCode(400).setMessage("该学院存在学生，不能删除"));
        }else
        {
            try{
                collegeMapper.deleteByCollege( college);
                return JSON.toJSONString(new Result<>().setCode(200).setMessage("删除成功"));
        }catch (Exception e){
                return JSON.toJSONString(new Result<>().setCode(400).setMessage("删除失败"));
            }
        }
    }
}
